package init

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"supplier/basic/config"
)

func init() {
	Viper()
	Nacos()
	Mysql()
	Redis()
}

var NaT config.T

func Redis() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     NaT.Redis.Addr,
		Password: NaT.Redis.Password, // no password set
		DB:       NaT.Redis.Db,       // use default DB
	})

	err := config.Rdb.Set(context.Background(), "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}
}

func Mysql() {
	var err error
	na := NaT.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		na.User, na.Password, na.Addr, na.Port, na.Data)

	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return
	}
	fmt.Println("mysql init success")
}

func Viper() {
	viper.SetConfigFile("./basic/config/config.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	err = viper.Unmarshal(&config.Conf)
	if err != nil {
		panic(err)
	}
	fmt.Println("创建成功", config.Conf)

}

func Nacos() {
	na := config.Conf.Nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         na.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      na.IpAddr,
			ContextPath: "/nacos",
			Port:        na.Port,
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: na.DataId,
		Group:  na.Group})
	if err != nil {
		panic(err)
	}
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: na.DataId,
		Group:  na.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal([]byte(content), &NaT)

	if err != nil {
		panic(err)
	}
}
